﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NetCoreBBS.Entities;
using NetCoreBBS.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

namespace NetCoreBBS
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    // Requires using RazorPagesMovie.Models;
                    InitializeNetCoreBBSDatabase(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }

        static void InitializeNetCoreBBSDatabase(IServiceProvider serviceProvider)
        {
            using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var db = serviceScope.ServiceProvider.GetService<DataContext>();
                db.Database.Migrate();
                if (db.TopicNodes.Count() == 0)
                {
                    db.TopicNodes.AddRange(GetTopicNodes());
                    db.SaveChanges();
                }

                var _roleManager = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
                var roleList = GetRoles();
                foreach (var role in roleList)
                {
                    _roleManager.CreateAsync(role).Wait();
                }

                var _userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
                var userList = GetUsers();
                foreach (var user in userList)
                {
                    var result = _userManager.CreateAsync(user, user.PasswordHash).Result;
                    if (result.Succeeded)
                    {
                        //设置用户角色
                        _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "Admin")).Wait();
                    }
                }
            }
        }

        static IEnumerable<TopicNode> GetTopicNodes()
        {
            return new List<TopicNode>()
            {
                new TopicNode() { Name="信息", NodeName="1", ParentId=0, Order=1, CreateOn=DateTime.Now },
                new TopicNode() { Name="政策", NodeName="2", ParentId=1, Order=1, CreateOn=DateTime.Now, Description="市场政策"},

            };
        }

        static IEnumerable<ApplicationUser> GetUsers()
        {
            return new List<ApplicationUser>()
            {
                new ApplicationUser
                {
                     CreateTime = DateTime.Now,
                     Email = "18653591936@wo.cn",
                     Name = "Admin",
                     PhoneNumber = "18653591936",
                     UserName = "18653591936",
                     PasswordHash = "Xxh!@#123"
                }
            };

        }

        static IEnumerable<IdentityRole> GetRoles()
        {
            return new List<IdentityRole>()
            {
                new IdentityRole("Admin"),
                new IdentityRole("Normal")
            };
        }


        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}
